// simulation.worker.ts
import { CSG } from 'three-csg-ts'
import * as THREE from "three";
// import type { WorkerMessage } from './types'

interface WorkerMessage {
    type: 'booleanOperation' | 'meshUpdate'
    data: any
  }

// 处理布尔运算
const processBooleanOperation = (
  workpieceData: any,
  toolData: any
) => {
  // 创建几何体
  const workpieceGeometry = createGeometryFromData(workpieceData)
  const toolGeometry = createGeometryFromData(toolData)

  // 创建网格
  const workpieceMesh = new THREE.Mesh(workpieceGeometry)
  const toolMesh = new THREE.Mesh(toolGeometry)
  
  // 应用变换矩阵
  const matrix = new THREE.Matrix4().fromArray(toolData.matrix)
  toolMesh.applyMatrix4(matrix)

  // 执行布尔差集运算
  const result = CSG.subtract(workpieceMesh, toolMesh)
  
  // 提取结果数据
  const resultGeometry = result.geometry
  resultGeometry.computeVertexNormals()
  
  return {
    positions: Array.from(resultGeometry.attributes.position.array),
    normals: Array.from(resultGeometry.attributes.normal.array),
    indices: Array.from(resultGeometry.index?.array || []),
    vertexCount: resultGeometry.attributes.position.count
  }
}

// 从数据创建几何体
const createGeometryFromData = (data: any) => {
  const geometry = new THREE.BufferGeometry()
  
  geometry.setAttribute(
    'position',
    new THREE.BufferAttribute(new Float32Array(data.positions), 3)
  )
  
  geometry.setAttribute(
    'normal',
    new THREE.BufferAttribute(new Float32Array(data.normals), 3)
  )
  
  if (data.indices.length > 0) {
    geometry.setIndex(
      new THREE.BufferAttribute(new Uint32Array(data.indices), 1)
    )
  }
  
  return geometry
}

// Worker消息处理
self.onmessage = (event: MessageEvent<WorkerMessage>) => {
  const { type, data } = event.data
  
  if (type === 'booleanOperation') {
    const result = processBooleanOperation(data.workpiece, data.tool)
    
    self.postMessage({
      type: 'meshUpdate',
      data: result
    })
  }
}